import math
import time
import uuid

import redis.exceptions
from redis.client import Redis

mconn = Redis(host="192.168.35.111", port=6379, db=0, decode_responses=True)


def acquire_semaphore(conn, semname, limit, timeout=10):
    identifire = str(uuid.uuid4())
    now = time.time()
    pipline = conn.pipeline(True)
    pipline.zremrangebyscore(semname, '-inf', now - timeout)
    pipline.zadd(semname, {identifire: now})
    pipline.zrank(semname, identifire)
    result = pipline.execute()
    if result[-1] < limit:
        return identifire
    conn.zrem(semname, identifire)
    return None


def release_semaphore(conn, semname, identifire):
    return conn.zrem(semname, identifire)


def acquire_fair_semaphore(conn, semname, limit, timeout=10):
    identifire = str(uuid.uuid4())
    czset = semname + ":owner"
    ctr = semname + ":counter"
    now = time.time()
    pipe = conn.pipeline(True)
    pipe.zremrangebyscore(semname, '-inf', now - timeout)
    pipe.zinterstore(czset, {czset: 1, semname: 0})
    pipe.incr(ctr)
    counter = pipe.execute()[-1]
    pipe.zadd(semname, {identifire: now})
    pipe.zadd(czset, {identifire: counter})
    pipe.zrank(czset, identifire)
    if pipe.execute()[-1] < limit:
        return identifire
    pipe.zrem(semname, identifire)
    pipe.zrem(czset, identifire)
    pipe.execute()
    return None


def release_fair_semaphore(conn, semname, identifire):
    pipe = conn.pipeline(True)
    pipe.zrem(semname, identifire)
    pipe.zrem(semname + ':owner', identifire)
    return pipe.execute()[0]


def refresh_fair_semaphore(conn, semname, identifire):
    if conn.zadd(semname, {identifire: time.time()}):
        release_fair_semaphore(conn, semname, identifire)
        return False
    return True


def acquire_lock_with_timeout(conn, lockname, acquire_timeout=10, lock_timeout=10):
    identifier = str(uuid.uuid4())
    lockname = 'lock:' + lockname
    lock_timeout = int(math.ceil(lock_timeout))
    end = time.time() + acquire_timeout
    while time.time() < end:
        if conn.setnx(lockname, identifier):
            conn.expire(lockname, lock_timeout)
            return identifier
        elif not conn.ttl(lockname):
            conn.expire(lockname, lock_timeout)
        time.sleep(0.001)
    return False


def release_lock(conn, lockname, identifier):
    pipe = conn.pipeline(True)
    lockname = 'lock:' + lockname
    while True:
        try:
            pipe.watch(lockname)
            if pipe.get(lockname) == identifier:
                pipe.multi()
                pipe.delete(lockname)
                pipe.execute()
            pipe.unwatch()
            break
        except redis.exceptions.WatchError:
            pass
    return False


def acquire_semaphore_with_lock(conn, semname, limit, timeout=10):
    ident = acquire_lock_with_timeout(conn, semname, acquire_timeout=1)
    if ident:
        try:
            return acquire_fair_semaphore(conn, semname, limit, timeout)
        finally:
            release_lock(conn, semname, ident)


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # ident = acquire_semaphore(mconn, "semaphore:logs", 5)
    # release_semaphore(mconn, "semaphore:logs", ident)
    ident = acquire_fair_semaphore(mconn, "semaphore:logs", 5, 100)
    refresh_fair_semaphore(mconn, "semaphore:logs", ident)
    print_hi(release_fair_semaphore(mconn, "semaphore:logs", ident))
    print_hi(ident)

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
